package madixin.t2;


class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(-1);
        ListNode curNode = dummy;
        ListNode p = l1;
        ListNode q = l2;
        int add = 0;
        while (p != null || q != null) {
            int cur = 0;
            if (p == null) {
                cur = q.val + add;
                q = q.next;
            } else if (q == null) {
                cur = p.val + add;
                p = p.next;
            } else {
                cur = p.val + q.val + add;
                p = p.next;
                q = q.next;
            }

            ListNode nextNode = new ListNode(cur % 10);
            curNode.next = nextNode;
            curNode = nextNode;
            add = cur / 10;
        }

        if (add == 1) {
            ListNode nextNode = new ListNode(1);
            curNode.next = nextNode;
        }
        return dummy.next;
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        ListNode l1_1 = new ListNode(2);
        ListNode l1_2 = new ListNode(4);
        ListNode l1_3 = new ListNode(3);
        l1_1.next = l1_2;
        l1_2.next = l1_3;

        ListNode l2_1 = new ListNode(5);
        ListNode l2_2 = new ListNode(6);
        ListNode l2_3 = new ListNode(4);
        l2_1.next = l2_2;
        l2_2.next = l2_3;

        ListNode res = s.addTwoNumbers(l1_1, l2_1);
        while (res != null) {
            System.out.println(res.val);
            res = res.next;
        }

    }
}